﻿using System;
using System.Diagnostics;
using System.Drawing;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System.Collections.Generic;
using System.IO;

namespace AndersLiu.MicrosoftOffice.PowerPoint
{
    public class PPTFile
    {
        private Presentation _ppt;

        public PPTFile(string path)
        {
            if (path == null)
                throw new ArgumentNullException("path");

            var app = new ApplicationClass();
            _ppt = app.Presentations.Open(
                path,                  // FileName
                MsoTriState.msoTrue,   // ReadOnly
                MsoTriState.msoFalse,  // Untitled
                MsoTriState.msoFalse   // WithWindow
                );
            Debug.Assert(_ppt != null);
        }

        public int SlidesCount
        {
            get { return _ppt.Slides.Count; }
        }

        public IEnumerable<PPTSimpleSlide> EnumSimpleSlides(int imgWidth, int imgHeight)
        {
            if (imgWidth < 0)
                throw new ArgumentOutOfRangeException("imgWidth");

            if (imgHeight < 0)
                throw new ArgumentOutOfRangeException("imgHeight");

            foreach (Slide slide in _ppt.Slides)
            {
                Image tempImg = null;
                string tempImgFile = null;
                Image picture = null;
                try
                {
                    tempImgFile = Path.GetTempFileName();
                    slide.Export(tempImgFile, "PNG", imgWidth, imgHeight);
                    tempImg = Image.FromFile(tempImgFile);
                    picture = new Bitmap(tempImg);
                    tempImg.Dispose();
                }
                finally
                {
                    if (tempImg != null)
                    {
                        tempImg.Dispose();
                        tempImg = null;
                    }

                    if (tempImgFile != null && File.Exists(tempImgFile))
                    {
                        File.Delete(tempImgFile);
                        tempImgFile = null;
                    }
                }

                string notes = slide.NotesPage.Shapes.Placeholders[2]
                    .TextFrame.TextRange.Text
                    .Replace("\r", Environment.NewLine);  // PPT uses '\r' as line break.

                yield return new PPTSimpleSlide(picture, notes);
            }
        }
    }

    public class PPTSimpleSlide
    {
        public Image Picture { get; private set; }
        public string Notes { get; private set; }

        internal PPTSimpleSlide(Image picture, string notes)
        {
            if (picture == null)
                throw new ArgumentNullException("picture");

            this.Picture = picture;
            this.Notes = notes;
        }
    }
}
